package org.autumn.sharding;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 读写分离
 */
public class TestReadWriteSeparate {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = getDataSource();

        Statement statement = dataSource.getConnection().createStatement();
        String sql = "insert into `user`(name) values ('mk')";

        // 这里不会进行同步数据 需要在数据库层面解决
        statement.execute(sql);


    }

    private static DataSource getDataSource() throws SQLException {
        // 配置真实数据源
        Map<String, DataSource> dataSourceMap = new HashMap<>();

        // 配置主库
        BasicDataSource masterDataSource = new BasicDataSource();
        masterDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        masterDataSource.setUrl("jdbc:mysql://121.5.167.184:3306/ds_master");
        masterDataSource.setUsername("root");
        masterDataSource.setPassword("immortal");
        dataSourceMap.put("ds_master", masterDataSource);

        // 配置第一个从库
        BasicDataSource slaveDataSource1 = new BasicDataSource();
        slaveDataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        slaveDataSource1.setUrl("jdbc:mysql://121.5.167.184:3306/ds_slave0");
        slaveDataSource1.setUsername("root");
        slaveDataSource1.setPassword("immortal");
        dataSourceMap.put("ds_slave0", slaveDataSource1);

        // 配置读写分离规则
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("ds_master_slave", "ds_master", Arrays.asList("ds_slave0"));
        Properties properties = new Properties();
        properties.put("sql.show", true);

        // 获取数据源对象
        return MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfig, properties);
    }
}
